Shoes.setup do
  gem 'rest-client'
end

require 'rest_client'
require 'rexml/document'

class BackendInterface
  
  def initialize (*backend_url)
    @backend_url = ENV['MODDB08_BACKEND_URL'] || 'http://localhost:9998/' # 'http://82.182.129.214/moddb_backend/test.svc/' #'http://localhost:9998/'
    @site = RestClient::Resource.new @backend_url
    
    debug @backend_url
    
  end
  
  def url
    @backend_url
  end
  
  def graceful_rescue
    begin
      yield
    rescue RestClient::Exception => e
      {:status => e.http_code}
    rescue Exception => e
      {:status => 503} # Service Unavailable
    end    
  end
  
  def list_all_tables
    graceful_rescue do
      {:status => 200, :tables => REXML::Document.new((resp = @site['tables/'].get :accept => 'application/xml')).elements.to_a('tables/table').map! {|t| t.attribute('name').to_s}}
    end
  end
  
  def list_all_columns_for_table(name)
    graceful_rescue do
      {:status => 200, :columns => REXML::Document.new(@site["tables/#{name}/columns/"].get :accept => 'application/xml').elements.to_a('columns/column').map { |c|
        {:name => c.attribute('name').to_s, :type => c.attribute('type').to_s, :mime => c.attribute('mime').to_s}
      }}
    end
  end
  
  def list_all_rows_for_table(name)
    graceful_rescue do
      {:status => 200, :rows => REXML::Document.new(@site["tables/#{name}/rows"].get :accept => 'application/xml').elements.to_a('rows/row').map {|r| r.attribute('id').to_s}}
    end
  end
  
  def read_row_entry_for_table(name, entry = {})
    graceful_rescue do
      {:status => 200, :entry => @site["tables/#{name}/rows/#{entry[:row]}/#{entry[:column_name]}"].get(:accept => entry[:column_mime]) }
    end
  end
  
  def write_row_entry_for_table(name, entry = {})
    graceful_rescue do
      @site["tables/#{name}/rows/#{entry[:row]}/#{entry[:column_name]}"].put entry[:entry]
      {:status => 201}
    end
  end
  
  def add_table(name)
    graceful_rescue do
      @site['tables/'].post "<?xml version=\"1.0\"?><table name=\"#{name}\"/>", :content_type => 'application/xml'
      {:status => 201}
    end
  end
  
  def add_column_for_table(name, col = {})
    graceful_rescue do
      @site["tables/#{name}/columns/"].post "<?xml version=\"1.0\"?><column name=\"#{col[:name]}\" type=\"#{col[:type]}\" mime=\"#{col[:mime]}\"/>", :content_type => 'application/xml'
      {:status => 201}
    end
  end
  
  def add_row_for_table(name)
    graceful_rescue do
      @site["tables/#{name}/rows/"].post "<?xml version=\"1.0\"?><row/>", :content_type => 'application/xml'
      {:status => 201}
    end
  end
  
  def del_table(name)
    graceful_rescue do
      @site["tables/#{name}"].delete
      {:status => 204}
    end
  end
  
  def del_row_for_table(name, row = {})
    graceful_rescue do
      @site["tables/#{name}/rows/#{row[:id]}"].delete
      {:status => 204}
    end
  end
  
end
